import { _decorator, animation, Component, Input, Node, tween, v2, v3, Vec2 } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('Bullet')
export class Bullet extends Component {
    @property(Node)
    bullet: Node;
    public monster: Node = null

    protected onLoad(): void {
        //监听怪物进入
        game.EventMgr.on(`bullet.attack_${this.bullet.uuid}`, this.getMonster, this)
    }
    protected onDestroy(): void {
        game.EventMgr.off(`bullet.attack_${this.bullet.uuid}`, this.getMonster, this)
    }

    //获取攻击的指定monster
    getMonster(node: Node) {
        this.monster = node
    }
    update(dt) {
        if (!this.monster) return
        //获取player位置
        let playerPos = this.monster.position
        //获取bullet的位置
        let bulletPos = this.bullet.position
        let radian = Math.atan2(playerPos.y - bulletPos.y, playerPos.x - bulletPos.x);  //导弹和目的地之间弧度
        //防止抖动
        if (Math.sqrt(Math.pow((playerPos.y - bulletPos.y), 2) + Math.pow((playerPos.x - bulletPos.x), 2)) < 20) return
        this.bullet.angle = radian * 180 / Math.PI;   //弧度转换成角度
        let moveSpeed = 20;                                    //移动速度
        let bulletPosX = bulletPos.x + Math.cos(radian) * moveSpeed;          //x变化
        let bulletPosY = bulletPos.y + Math.sin(radian) * moveSpeed;        //Y变化
        this.bullet.setPosition(bulletPosX, bulletPosY)

        //计算是否接触
        let dis = Math.sqrt(Math.pow((playerPos.y - bulletPos.y), 2) + Math.pow((playerPos.x - bulletPos.x), 2))
        if (dis < 20) {
            //相撞
            this.monster.active = false
            this.bullet.active = false
            console.log("撞击")
        }
    }
}



